<template>
  <div class="webrtc-demo">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item>
            <el-button type="primary" @click="onSubmit"
              >点击获取当前屏幕分享</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <video id="localdemo02" autoplay controls muted></video>
    </el-row>
  </div>
</template>

<script setup>
const formInline = ref({});
/**
 * 提交
 */
const handleError = (error) => {
  // alert("摄像头无法正常使用，请检查是否占用或缺失")
  console.log("navigator.MediaDevices error: ", error.message, error.name);
};
const onSubmit = async () => {
  let domId = "localdemo02";
  let video = document.getElementById(domId);
  let stream = video.srcObject;
  if (stream) {
    stream.getAudioTracks().forEach((e) => {
      stream.removeTracke(e);
    });
    stream.getVideoTracks().forEach((e) => {
      stream.removeTracke(e);
    });
  }
  let newStream = await getShareMedia();
  console.log("newStream", newStream);
  video.srcObject = newStream;
  video.muted = true;
};

/**
 * 获取屏幕共享媒体
 * @returns {Promise<MediaStream>}
 */
const getShareMedia = async () => {
  const constraints = {
    video: { width: 1920, height: 1080 },
    audio: true,
  };
  if (window.stream) {
    window.stream.getTracks().forEach((track) => {
      track.stop();
    });
  }
  return await navigator.mediaDevices
    .getDisplayMedia(constraints)
    .catch(handleError);
};
</script>

<style lang="scss" scoped>
.webrtc-demo {
  padding: 20px;
  position: relative;
}
#localdemo02 {
  width: 500px;
  height: 400px;
}
</style>
